<template>
  <div class="user-profile-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">个人中心</h2>
      <p class="page-subtitle">管理您的个人信息和账户设置</p>
    </div>

    <div class="profile-container">
      <!-- 头像和基本信息卡片 -->
      <el-card class="profile-card" shadow="hover">
        <div class="profile-header">
          <div class="avatar-section">
            <div class="avatar-container">
              <img
                :src="getAvatarUrl(userInfo.avatar)"
                alt="用户头像"
                class="user-avatar"
                @error="handleAvatarError"
              />
              <div class="avatar-overlay" @click="triggerAvatarUpload">
                <el-icon class="camera-icon"><Camera /></el-icon>
                <span class="upload-text">更换头像</span>
              </div>
            </div>
            <input
              ref="avatarInput"
              type="file"
              accept="image/*"
              style="display: none"
              @change="handleAvatarUpload"
            />
          </div>

          <div class="user-basic-info">
            <h3 class="user-name">{{ userInfo.full_name || userInfo.username }}</h3>
            <p class="user-role">普通用户</p>
            <div class="user-stats">
              <div class="stat-item">
                <span class="stat-label">用户ID</span>
                <span class="stat-value">{{ userInfo.user_id }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">注册时间</span>
                <span class="stat-value">{{ formatDate(userInfo.created_at) }}</span>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 个人信息编辑卡片 -->
      <el-card class="info-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <h3 class="card-title">
              <el-icon><User /></el-icon>
              个人信息
            </h3>
            <el-button
              v-if="!isEditing"
              type="primary"
              @click="startEdit"
              :icon="Edit"
            >
              编辑信息
            </el-button>
            <div v-else class="edit-actions">
              <el-button type="success" @click="saveChanges" :loading="saving">
                保存
              </el-button>
              <el-button @click="cancelEdit">取消</el-button>
            </div>
          </div>
        </template>

        <div class="info-form">
          <div class="form-row">
            <div class="form-item">
              <label class="form-label">
                <el-icon><User /></el-icon>
                用户名
              </label>
              <el-input
                v-if="isEditing"
                v-model="editForm.username"
                placeholder="请输入用户名"
              />
              <span v-else class="form-value">{{ userInfo.username }}</span>
            </div>

            <div class="form-item">
              <label class="form-label">
                <el-icon><Lock /></el-icon>
                密码
              </label>
              <el-input
                v-if="isEditing"
                v-model="editForm.password"
                type="password"
                placeholder="请输入新密码（不修改请留空）"
                show-password
              />
              <span v-else class="form-value">••••••••</span>
            </div>
          </div>

          <div class="form-row">
            <div class="form-item">
              <label class="form-label">
                <el-icon><UserFilled /></el-icon>
                全名
              </label>
              <el-input
                v-if="isEditing"
                v-model="editForm.full_name"
                placeholder="请输入真实姓名"
              />
              <span v-else class="form-value">{{ userInfo.full_name || '未设置' }}</span>
            </div>

            <div class="form-item">
              <label class="form-label">
                <el-icon><Phone /></el-icon>
                手机号码
              </label>
              <el-input
                v-if="isEditing"
                v-model="editForm.phone_number"
                placeholder="请输入手机号码"
              />
              <span v-else class="form-value">{{ userInfo.phone_number || '未设置' }}</span>
            </div>
          </div>

          <div class="form-row">
            <div class="form-item full-width">
              <label class="form-label">
                <el-icon><Message /></el-icon>
                邮箱地址
              </label>
              <el-input
                v-if="isEditing"
                v-model="editForm.email"
                placeholder="请输入邮箱地址"
              />
              <span v-else class="form-value">{{ userInfo.email || '未设置' }}</span>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 账户操作卡片 -->
      <el-card class="actions-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <h3 class="card-title">
              <el-icon><Setting /></el-icon>
              账户操作
            </h3>
          </div>
        </template>

        <div class="actions-content">
          <div class="action-item danger-action">
            <div class="action-info">
              <h4 class="action-title">注销账户</h4>
              <p class="action-desc">永久删除您的账户和所有相关数据，此操作不可恢复</p>
            </div>
            <el-button
              type="danger"
              plain
              @click="confirmDeleteAccount"
              :loading="deleting"
            >
              注销账户
            </el-button>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import { userInfoApi, updateUserInfoApi, deleteUserApi, uploadAvatarApi } from "@/utils/api";
import {
  User,
  UserFilled,
  Phone,
  Message,
  Lock,
  Edit,
  Setting,
  Camera
} from '@element-plus/icons-vue';

// 响应式数据
const userInfo = ref({});
const editForm = reactive({});
const isEditing = ref(false);
const saving = ref(false);
const deleting = ref(false);
const avatarInput = ref(null);

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

// 初始化用户信息
const init = async () => {
  try {
    const data = localStorage.getItem("user");
    const { user_id } = JSON.parse(data);
    const res = await userInfoApi({ user_id });

    if (res.code === 200 && res.orders && res.orders.length > 0) {
      userInfo.value = res.orders[0];
      // 初始化编辑表单
      Object.assign(editForm, {
        username: userInfo.value.username,
        password: '',
        full_name: userInfo.value.full_name,
        phone_number: userInfo.value.phone_number,
        email: userInfo.value.email
      });
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    ElMessage.error('获取用户信息失败');
  }
};

// 开始编辑
const startEdit = () => {
  isEditing.value = true;
  // 重新初始化编辑表单
  Object.assign(editForm, {
    username: userInfo.value.username,
    password: '',
    full_name: userInfo.value.full_name,
    phone_number: userInfo.value.phone_number,
    email: userInfo.value.email
  });
};

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false;
  // 重置表单
  Object.assign(editForm, {
    username: userInfo.value.username,
    password: '',
    full_name: userInfo.value.full_name,
    phone_number: userInfo.value.phone_number,
    email: userInfo.value.email
  });
};

// 保存更改
const saveChanges = async () => {
  try {
    saving.value = true;

    // 构建更新数据
    const updateData = {
      user_id: userInfo.value.user_id,
      username: editForm.username,
      full_name: editForm.full_name,
      phone_number: editForm.phone_number,
      email: editForm.email
    };

    // 如果密码不为空，则包含密码更新
    if (editForm.password.trim()) {
      updateData.password = editForm.password;
    }

    const res = await updateUserInfoApi(updateData);

    if (res.code === 200) {
      ElMessage.success('信息更新成功');
      // 更新本地数据
      Object.assign(userInfo.value, {
        username: editForm.username,
        full_name: editForm.full_name,
        phone_number: editForm.phone_number,
        email: editForm.email
      });

      // 更新本地存储
      const userData = JSON.parse(localStorage.getItem("user"));
      Object.assign(userData, updateData);
      localStorage.setItem("user", JSON.stringify(userData));

      isEditing.value = false;
    } else {
      ElMessage.error(res.message || '更新失败');
    }
  } catch (error) {
    console.error('更新用户信息失败:', error);
    ElMessage.error('更新失败，请重试');
  } finally {
    saving.value = false;
  }
};

// 触发头像上传
const triggerAvatarUpload = () => {
  avatarInput.value?.click();
};

// 处理头像上传
const handleAvatarUpload = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件');
    return;
  }

  // 验证文件大小（限制为2MB）
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过2MB');
    return;
  }

  try {
    // 创建FormData对象
    const formData = new FormData();
    formData.append('avatar', file);
    formData.append('user_id', userInfo.value.user_id);

    // 上传到服务器
    const res = await uploadAvatarApi(formData);

    if (res.code === 200) {
      // 更新本地头像显示
      userInfo.value.avatar = `http://localhost:3000${res.data.avatarUrl}`;
      ElMessage.success('头像上传成功');

      // 更新本地存储
      const userData = JSON.parse(localStorage.getItem("user"));
      userData.avatar = userInfo.value.avatar;
      localStorage.setItem("user", JSON.stringify(userData));
    } else {
      ElMessage.error(res.message || '头像上传失败');
    }
  } catch (error) {
    console.error('头像上传失败:', error);
    ElMessage.error('头像上传失败，请重试');
  }

  // 清空input值，允许重复选择同一文件
  event.target.value = '';
};

// 获取头像URL
const getAvatarUrl = (avatar) => {
  if (!avatar) return defaultAvatar;

  // 如果已经是完整URL，直接返回
  if (avatar.startsWith('http')) return avatar;

  // 如果是相对路径，拼接服务器地址
  if (avatar.startsWith('/uploads')) {
    return `http://localhost:3000${avatar}`;
  }

  // 其他情况返回默认头像
  return defaultAvatar;
};

// 头像加载错误处理
const handleAvatarError = (event) => {
  event.target.src = defaultAvatar;
};

// 确认删除账户
const confirmDeleteAccount = async () => {
  try {
    await ElMessageBox.confirm(
      '此操作将永久删除您的账户和所有相关数据，且无法恢复。确定要继续吗？',
      '危险操作',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error',
        confirmButtonClass: 'el-button--danger'
      }
    );

    deleting.value = true;
    const res = await deleteUserApi({ user_id: userInfo.value.user_id });

    if (res.code === 200) {
      ElMessage.success('账户注销成功');
      // 清除本地存储
      localStorage.removeItem('user');
      localStorage.removeItem('token');
      // 跳转到登录页面
      setTimeout(() => {
        window.location.href = '/';
      }, 1500);
    } else {
      ElMessage.error(res.message || '注销失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('注销账户失败:', error);
      ElMessage.error('注销失败，请重试');
    }
  } finally {
    deleting.value = false;
  }
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '未知';
  return new Date(dateStr).toLocaleDateString('zh-CN');
};

// 组件挂载时初始化
onMounted(() => {
  init();
});
</script>

<style lang="less" scoped>
.user-profile-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 24px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 8px 0;
  }

  .page-subtitle {
    color: #909399;
    margin: 0;
    font-size: 14px;
  }
}

.profile-container {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.profile-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;

  :deep(.el-card__body) {
    padding: 32px;
  }
}

.profile-header {
  display: flex;
  align-items: center;
  gap: 32px;
}

.avatar-section {
  position: relative;
}

.avatar-container {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    transform: scale(1.05);

    .avatar-overlay {
      opacity: 1;
    }
  }
}

.user-avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
  border: 4px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  border-radius: 50%;

  .camera-icon {
    font-size: 24px;
    color: white;
    margin-bottom: 4px;
  }

  .upload-text {
    color: white;
    font-size: 12px;
  }
}

.user-basic-info {
  flex: 1;

  .user-name {
    font-size: 28px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 8px 0;
  }

  .user-role {
    color: #909399;
    font-size: 16px;
    margin: 0 0 20px 0;
  }

  .user-stats {
    display: flex;
    gap: 32px;

    .stat-item {
      display: flex;
      flex-direction: column;

      .stat-label {
        font-size: 14px;
        color: #909399;
        margin-bottom: 4px;
      }

      .stat-value {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
    }
  }
}

.info-card, .actions-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;

  :deep(.el-card__header) {
    padding: 24px 32px;
    background: #fafbfc;
    border-bottom: 1px solid #ebeef5;
  }

  :deep(.el-card__body) {
    padding: 32px;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .card-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    margin: 0;

    .el-icon {
      color: #409eff;
    }
  }

  .edit-actions {
    display: flex;
    gap: 12px;
  }
}

.info-form {
  .form-row {
    display: flex;
    gap: 24px;
    margin-bottom: 24px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .form-item {
    flex: 1;

    &.full-width {
      flex: none;
      width: 100%;
    }

    .form-label {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 14px;
      font-weight: 500;
      color: #606266;
      margin-bottom: 8px;

      .el-icon {
        color: #909399;
      }
    }

    .form-value {
      display: block;
      padding: 12px 16px;
      background: #f5f7fa;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      color: #303133;
      font-size: 14px;
      min-height: 40px;
      line-height: 16px;
    }
  }
}

.actions-content {
  .action-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border: 1px solid #ebeef5;
    border-radius: 8px;

    &.danger-action {
      border-color: #fde2e2;
      background: #fef5f5;
    }

    .action-info {
      flex: 1;

      .action-title {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
        margin: 0 0 8px 0;
      }

      .action-desc {
        font-size: 14px;
        color: #909399;
        margin: 0;
        line-height: 1.5;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .user-profile-page {
    padding: 16px;
  }

  .profile-header {
    flex-direction: column;
    text-align: center;
    gap: 20px;
  }

  .user-stats {
    justify-content: center;
    gap: 20px !important;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .edit-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .info-form {
    .form-row {
      flex-direction: column;
      gap: 16px;
    }
  }

  .action-item {
    flex-direction: column !important;
    align-items: flex-start !important;
    gap: 16px;

    .action-info {
      text-align: left;
    }

    .el-button {
      width: 100%;
    }
  }

  .info-card, .actions-card {
    :deep(.el-card__header) {
      padding: 20px;
    }

    :deep(.el-card__body) {
      padding: 20px;
    }
  }

  .profile-card {
    :deep(.el-card__body) {
      padding: 24px;
    }
  }
}

@media (max-width: 480px) {
  .avatar-container {
    width: 100px;
    height: 100px;
  }

  .user-name {
    font-size: 24px !important;
  }

  .user-stats {
    flex-direction: column;
    gap: 12px !important;

    .stat-item {
      text-align: center;
    }
  }
}
</style>
